<script lang="ts" setup>
import { reactive, ref, shallowRef, onMounted, onActivated } from 'vue'
import { useMap } from '@/hooks/useMap'
import { useActivated } from '@/hooks/useActivated'
import { useRoute } from 'vue-router'
import SearchPlace from '@/components/map/SearchPlace.vue'
import bikeImg from '@/assets/map/bikeLocation/bike.png'
import { queryBike } from '@/api/bike'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage } from 'element-plus'
defineOptions({
  name: 'LongBikeLocation'
})
const route = useRoute()
const center = reactive({
  longtitude: Number(route.query.longtitude),
  latitude: Number(route.query.latitude),
  bikeCode: route.query.bikeCode,
  type: '0'
})
const isInit = ref<boolean>(false)
const address = ref<any>('')
const mapContainer = ref<HTMLDivElement>()
const marker = shallowRef<AMap.Marker>()
const infoWindow = shallowRef<AMap.InfoWindow>()
const { map, auto, initAmap, getAddress, placeSearch } = useMap(mapContainer, [
  center.longtitude,
  center.latitude
])
/** 地图初始化 */
const init = async () => {
  isInit.value = await initAmap()
  handleCoverInit(center)
}
const handleCoverInit = async (params?: any) => {
  if (isInit.value && map.value) {
    map.value.clearMap()
    address.value = await getAddress(params?.longtitude, params?.latitude)
    marker.value = new AMap.Marker({
      position: new AMap.LngLat(center.longtitude, center.latitude),
      map: map.value,
      icon: new AMap.Icon({
        image: bikeImg,
        imageSize: new AMap.Size(59, 63),
        size: new AMap.Size(59, 63)
      }),
      offset: new AMap.Pixel(-30, -63)
    })
    infoWindow.value = new AMap.InfoWindow({
      position: new AMap.LngLat(center.longtitude, center.latitude),
      isCustom: true,
      autoMove: true,
      offset: new AMap.Pixel(0, -60),
      content: createContent()
    })
    infoWindow.value.open(map.value, [center.longtitude, center.latitude])
    marker.value.on('click', () => {
      if (infoWindow.value?.getIsOpen()) {
        infoWindow.value.close()
      } else {
        infoWindow.value?.open(map.value!, [center.longtitude, center.latitude])
      }
    })
    const mapContainer = document.getElementById('map-container')
    mapContainer?.addEventListener('click', handleInfoWindowClick)
  }
}
const createContent = () => {
  return `<div class="map-infowindow_location">
                  <span>车辆位置:${address.value}<span class="red-refresh">刷新</span></span>
              </div>
              `
}
const handleInfoWindowClick = (event: any) => {
  if (event.target.className.includes('red-refresh')) {
    refresh()
  }
}
const getLongBikeData = async () => {
  try {
    const res = await queryBike({
      token: getToken() ?? '',
      bikeCode: route.query.bikeCode as string,
      type: '0',
      storeId: '',
      pageNum: 1,
      pageSize: 10
    })
    if (res.statusCode === '0') {
      ElMessage.success('刷新成功')
      return [Number(res.data.list[0].longtitude), Number(res.data.list[0].latitude)]
    } else {
      ElMessage.warning('刷新失败')
      return [center.longtitude, center.latitude]
    }
  } catch (error) {
    console.error(error)
  }
}
const refresh = async () => {
  // 更新地址信息的逻辑
  const res = await getLongBikeData()
  center.longtitude = res![0]
  center.latitude = res![0]
  map.value?.clearMap()
  handleCoverInit(center)
}
onMounted(() => {
  init()
})
/** 处理是否缓存 */
useActivated(
  center,
  { center },
  [
    { key: 'longtitude', path: 'center.longtitude' },
    { key: 'latitude', path: 'center.latitude' },
    { key: 'bikeCode', path: 'center.bikeCode' },
    { key: 'type', path: 'center.type' }
  ],
  handleCoverInit,
  ['type']
)
onActivated(() => {
  center.longtitude = Number(route.query.longtitude)
  center.latitude = Number(route.query.latitude)
  center.bikeCode = route.query.bikeCode
})
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container">
      <search-place :auto="auto" :map="map!" :place-search="placeSearch" />
    </div>
  </div>
</template>

<style scoped>
:deep(.red-refresh) {
  color: #ff6d75;
  cursor: pointer;
  margin-left: 10px;
}
</style>
